<template>
  <div class="color-picker-tool">
    <div class="tool-header">
      <h1>颜色选择器</h1>
      <p>在线颜色选择和格式转换工具</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 颜色选择区域 -->
        <el-col :span="12">
          <div class="color-picker-section">
            <div class="section-header">
              <h3>颜色选择</h3>
            </div>
            
            <div class="color-picker-container">
              <el-color-picker
                v-model="selectedColor"
                @change="handleColorChange"
                :predefine="predefineColors"
                show-alpha
                size="large"
              />
            </div>
            
            <div class="color-preview" :style="{ backgroundColor: selectedColor }">
              <div class="color-info">
                <h4>{{ selectedColor || '#000000' }}</h4>
                <p>当前选择的颜色</p>
              </div>
            </div>
          </div>

          <!-- 颜色格式转换 -->
          <div class="format-conversion">
            <h3>格式转换</h3>
            
            <div class="format-item">
              <label>HEX:</label>
              <el-input
                v-model="colorFormats.hex"
                @input="updateFromHex"
                placeholder="#000000"
              />
            </div>
            
            <div class="format-item">
              <label>RGB:</label>
              <el-input
                v-model="colorFormats.rgb"
                @input="updateFromRgb"
                placeholder="rgb(0, 0, 0)"
              />
            </div>
            
            <div class="format-item">
              <label>HSL:</label>
              <el-input
                v-model="colorFormats.hsl"
                @input="updateFromHsl"
                placeholder="hsl(0, 0%, 0%)"
              />
            </div>
            
            <div class="format-item">
              <label>HSV:</label>
              <el-input
                v-model="colorFormats.hsv"
                @input="updateFromHsv"
                placeholder="hsv(0, 0%, 0%)"
              />
            </div>
          </div>
        </el-col>

        <!-- 颜色信息区域 -->
        <el-col :span="12">
          <div class="color-info-section">
            <div class="section-header">
              <h3>颜色信息</h3>
              <div class="actions">
                <el-button @click="copyColor" size="small" :disabled="!selectedColor">复制颜色</el-button>
                <el-button @click="randomColor" size="small" type="primary">随机颜色</el-button>
              </div>
            </div>
            
            <div class="color-details">
              <div class="detail-item">
                <span class="label">颜色名称:</span>
                <span class="value">{{ colorName }}</span>
              </div>
              
              <div class="detail-item">
                <span class="label">亮度:</span>
                <span class="value">{{ brightness }}%</span>
              </div>
              
              <div class="detail-item">
                <span class="label">对比度:</span>
                <span class="value">{{ contrast }}</span>
              </div>
            </div>
            
            <div class="color-palette">
              <h4>调色板</h4>
              <div class="palette-grid">
                <div 
                  v-for="color in colorPalette" 
                  :key="color"
                  class="palette-color"
                  :style="{ backgroundColor: color }"
                  @click="selectColor(color)"
                  :title="color"
                ></div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 颜色历史 -->
      <div class="color-history">
        <h3>颜色历史</h3>
        <div class="history-colors">
          <div 
            v-for="(color, index) in colorHistory" 
            :key="index"
            class="history-color"
            :style="{ backgroundColor: color }"
            @click="selectColor(color)"
            :title="color"
          ></div>
        </div>
        <el-button @click="clearHistory" size="small" type="danger" plain>清空历史</el-button>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>颜色格式说明：</h4>
            <ul>
              <li><strong>HEX：</strong>十六进制颜色值，如 #FF0000</li>
              <li><strong>RGB：</strong>红绿蓝颜色值，如 rgb(255, 0, 0)</li>
              <li><strong>HSL：</strong>色相饱和度亮度，如 hsl(0, 100%, 50%)</li>
              <li><strong>HSV：</strong>色相饱和度明度，如 hsv(0, 100%, 100%)</li>
            </ul>
            
            <h4>使用场景：</h4>
            <ul>
              <li>网页设计中的颜色选择</li>
              <li>CSS样式开发</li>
              <li>UI设计配色</li>
              <li>品牌色彩管理</li>
            </ul>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

const selectedColor = ref('#409EFF')
const colorHistory = ref([])

const predefineColors = ref([
  '#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1',
  '#1e90ff', '#c71585', '#ff0000', '#ffa500', '#ffff00',
  '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#000000',
  '#ffffff', '#808080', '#800000', '#808000', '#008000'
])

const colorFormats = ref({
  hex: '#409EFF',
  rgb: 'rgb(64, 158, 255)',
  hsl: 'hsl(210, 100%, 63%)',
  hsv: 'hsv(210, 75%, 100%)'
})

const colorName = computed(() => {
  const colorMap = {
    '#FF0000': '红色',
    '#00FF00': '绿色', 
    '#0000FF': '蓝色',
    '#FFFF00': '黄色',
    '#FF00FF': '洋红',
    '#00FFFF': '青色',
    '#000000': '黑色',
    '#FFFFFF': '白色',
    '#808080': '灰色'
  }
  return colorMap[selectedColor.value?.toUpperCase()] || '自定义颜色'
})

const brightness = computed(() => {
  if (!selectedColor.value) return 0
  const hex = selectedColor.value.replace('#', '')
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  return Math.round((r * 299 + g * 587 + b * 114) / 1000)
})

const contrast = computed(() => {
  if (!selectedColor.value) return 'N/A'
  const hex = selectedColor.value.replace('#', '')
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
  return luminance > 0.5 ? '深色' : '浅色'
})

const colorPalette = computed(() => {
  if (!selectedColor.value) return []
  const baseColor = selectedColor.value
  const variations = []
  
  // 生成颜色变化
  for (let i = 0; i < 12; i++) {
    const hue = (i * 30) % 360
    variations.push(`hsl(${hue}, 70%, 50%)`)
  }
  
  return variations
})

const handleColorChange = (color) => {
  if (color) {
    updateColorFormats(color)
    addToHistory(color)
  }
}

const updateColorFormats = (color) => {
  if (!color) return
  
  // 更新HEX
  colorFormats.value.hex = color
  
  // 转换RGB
  const hex = color.replace('#', '')
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  colorFormats.value.rgb = `rgb(${r}, ${g}, ${b})`
  
  // 转换HSL
  const hsl = rgbToHsl(r, g, b)
  colorFormats.value.hsl = `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`
  
  // 转换HSV
  const hsv = rgbToHsv(r, g, b)
  colorFormats.value.hsv = `hsv(${hsv.h}, ${hsv.s}%, ${hsv.v}%)`
}

const rgbToHsl = (r, g, b) => {
  r /= 255
  g /= 255
  b /= 255
  
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  let h, s, l = (max + min) / 2
  
  if (max === min) {
    h = s = 0
  } else {
    const d = max - min
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
    
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break
      case g: h = (b - r) / d + 2; break
      case b: h = (r - g) / d + 4; break
    }
    h /= 6
  }
  
  return {
    h: Math.round(h * 360),
    s: Math.round(s * 100),
    l: Math.round(l * 100)
  }
}

const rgbToHsv = (r, g, b) => {
  r /= 255
  g /= 255
  b /= 255
  
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  const diff = max - min
  
  let h = 0
  if (diff !== 0) {
    if (max === r) h = ((g - b) / diff) % 6
    else if (max === g) h = (b - r) / diff + 2
    else h = (r - g) / diff + 4
  }
  
  return {
    h: Math.round(h * 60),
    s: Math.round(max === 0 ? 0 : (diff / max) * 100),
    v: Math.round(max * 100)
  }
}

const updateFromHex = (hex) => {
  if (hex && /^#[0-9A-Fa-f]{6}$/.test(hex)) {
    selectedColor.value = hex
    updateColorFormats(hex)
  }
}

const updateFromRgb = (rgb) => {
  const match = rgb.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/)
  if (match) {
    const r = parseInt(match[1])
    const g = parseInt(match[2])
    const b = parseInt(match[3])
    const hex = `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
    selectedColor.value = hex
    updateColorFormats(hex)
  }
}

const updateFromHsl = (hsl) => {
  const match = hsl.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/)
  if (match) {
    const h = parseInt(match[1])
    const s = parseInt(match[2]) / 100
    const l = parseInt(match[3]) / 100
    
    const c = (1 - Math.abs(2 * l - 1)) * s
    const x = c * (1 - Math.abs((h / 60) % 2 - 1))
    const m = l - c / 2
    
    let r, g, b
    if (h < 60) [r, g, b] = [c, x, 0]
    else if (h < 120) [r, g, b] = [x, c, 0]
    else if (h < 180) [r, g, b] = [0, c, x]
    else if (h < 240) [r, g, b] = [0, x, c]
    else if (h < 300) [r, g, b] = [x, 0, c]
    else [r, g, b] = [c, 0, x]
    
    const hex = `#${Math.round((r + m) * 255).toString(16).padStart(2, '0')}${Math.round((g + m) * 255).toString(16).padStart(2, '0')}${Math.round((b + m) * 255).toString(16).padStart(2, '0')}`
    selectedColor.value = hex
    updateColorFormats(hex)
  }
}

const updateFromHsv = (hsv) => {
  // HSV转换逻辑
  ElMessage.info('HSV转换功能开发中')
}

const selectColor = (color) => {
  selectedColor.value = color
  updateColorFormats(color)
  addToHistory(color)
}

const addToHistory = (color) => {
  if (!colorHistory.value.includes(color)) {
    colorHistory.value.unshift(color)
    if (colorHistory.value.length > 20) {
      colorHistory.value.pop()
    }
  }
}

const copyColor = async () => {
  if (!selectedColor.value) {
    ElMessage.warning('没有可复制的颜色')
    return
  }
  
  try {
    await navigator.clipboard.writeText(selectedColor.value)
    ElMessage.success('颜色已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const randomColor = () => {
  const randomHex = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
  selectedColor.value = randomHex
  updateColorFormats(randomHex)
  addToHistory(randomHex)
  ElMessage.success('已生成随机颜色')
}

const clearHistory = () => {
  colorHistory.value = []
  ElMessage.info('颜色历史已清空')
}

// 初始化
updateColorFormats(selectedColor.value)
</script>

<style scoped>
.color-picker-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.color-picker-section,
.color-info-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.color-picker-container {
  text-align: center;
  margin-bottom: 20px;
}

.color-preview {
  height: 120px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  margin-bottom: 20px;
}

.color-info h4 {
  font-size: 1.5rem;
  margin: 0 0 5px 0;
}

.color-info p {
  margin: 0;
  opacity: 0.9;
}

.format-conversion {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.format-conversion h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.2rem;
}

.format-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 15px;
}

.format-item label {
  min-width: 50px;
  font-weight: 500;
  color: #333;
}

.format-item .el-input {
  flex: 1;
}

.color-details {
  margin-bottom: 30px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  font-weight: 500;
  color: #666;
}

.detail-item .value {
  font-weight: bold;
  color: #333;
}

.color-palette h4 {
  color: #333;
  margin-bottom: 15px;
}

.palette-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
}

.palette-color {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.palette-color:hover {
  border-color: #409EFF;
  transform: scale(1.1);
}

.color-history {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  margin: 30px 0;
}

.color-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.2rem;
}

.history-colors {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.history-color {
  width: 30px;
  height: 30px;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.history-color:hover {
  border-color: #409EFF;
  transform: scale(1.1);
}

.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .format-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .palette-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
</style>
